$(document).ready(function() {


	//初始化按钮
	$("button").button();
	
	//设置渐入渐出时间
	var timeIn=2000;
	var timeOut=4000;
	
	//记录下拉框选中的房间号（也就是表格名）
	var tbname=$("#selectRoom").find("option:selected").text();
	//将选择的表名存储起来
	$("#selectRoom").data("tbname",tbname);
	
	showInformation("当前选择的教室为："+tbname,timeIn,timeOut);
	
	
	//当选项改变时
	$("#selectRoom").change(function(){
		//将改变的选项保存到变量中
		$("#selectRoom").data("tbname",$("#selectRoom").find("option:selected").text());
		//先在前端清空所有的预约
		$("#calendar").weekCalendar("clear");
		
		//重新载入预约表,要同步
		talkWithServer("action/deal.php","load",$("#selectRoom").data("tbname"),2,0,false,function(data){
				for(i=0;i<data.length;i++)
				{
					$("#calendar").weekCalendar("updateEvent",data[i]);
				}
				var str="你选择的教室为："+$("#selectRoom").data("tbname");
				showInformation(str,timeIn,timeOut);	
		});		
	});	

   var $calendar = $('#calendar');


   $calendar.weekCalendar({
       displayOddEven:true,
      timeslotsPerHour : 4,
	  timeslotHeight:30,
      firstDayOfWeek : 1,
	  scrollToHourMillis:1500,
	  use24Hour:true,
	  dateFormat:"Y-M-d",
	  timeFormat:"H:i",
      businessHours :{start: 8, end: 23, limitDisplay: true },
	  minDate:Date.today().add(-30).days(),
	  maxDate:Date.today().add(30).days(),
      daysToShow : 7,
      switchDisplay: {'当天': 1, '3天': 3, '工作日': 5, '整周': 7},
	  newEventText:"创建新日程",
	  shortMonths:['1','2','3','4','5','6','7','8','9','10','11','12'],
	  longMonths:['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
	  longDays:['星期天','星期一','星期二','星期三','星期四','星期五','星期六'],	

      title: function(daysToShow) {
			return daysToShow == 1 ? '%date%' : '%start%<---->%end%';
      },
      height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 1;
      },
      eventRender : function(calEvent, $event) {
			//默认渲染成另外的颜色		  
			 $event.css("backgroundColor","#C1D31B");
			 $event.find(".wc-time").css({
				 	"backgroundColor":"#BED112",
					"border":"2px dashed #1232D1"
				 });
			 $event.find(".wc-title").css({
				 	"color":"#F95A36"
				 });
		 
		 //过期事件
         if (calEvent.end.getTime() < new Date().getTime()) {
            $event.css("backgroundColor", "#aaa");
            $event.find(".wc-time").css({
               "backgroundColor" : "#999",
               "border" : "1px solid #888"
            });
         }
      },
	  
	  eventAfterRender:function(calEvent,$event){
			 $calendar.weekCalendar("removeUnsavedEvents");
	  },
      draggable : function(calEvent, $event) {
		  //只有同一个部门的人才可以拖动
         return false;
      },
      resizable : function(calEvent, $event) {
         return false;
      },
      eventNew : function(calEvent, $event) {		  
		  return false;

      },
      eventDrop : function(calEvent, $event) {
		  return false;
        
      },
      eventResize : function(calEvent, $event) {
		　return false;		  
      },
      eventClick : function(calEvent, $event) {
			return false;
      },
      eventMouseover : function(calEvent, $event) {
      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {

      },

      reachedmindate: function($calendar, date){
        showInformation("不能查看一个月以前的记录！",timeIn,timeOut);
      },
      reachedmaxdate: function($calendar, date){
        showInformation("不能预约一个月以后的日期！",timeIn,timeOut);
      },
	  
      data : function(start, end, callback) {
         callback(getEventData());
      }
   });


   function getEventData() {
	   
		//与服务器通话，由于要等数据到达，所以需要同步，让async为false
		 talkWithServer("action/deal.php","load",$("#selectRoom").data("tbname"),2,0,false,function(data){
				var dataArr=new Array();
				
				for(i=0;i<data.length;i++)
				{
					dataArr[i]=data[i];
				}
				//将数据存储到某个选择器上
				$("#calendar").data("initData",{events:dataArr});
		 });
		 
		 return $("#calendar").data("initData");
   }


   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      $startTimeField.empty();
      $endTimeField.empty();

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

         $timestampsOfOptions.start[timeslotTimes[i].startFormatted] = startTime.getTime();
         $timestampsOfOptions.end[timeslotTimes[i].endFormatted] = endTime.getTime();

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");
   var $timestampsOfOptions = {start:[],end:[]};

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $timestampsOfOptions.start[$(this).find(":selected").text()];
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $timestampsOfOptions.end[$(this).text()];
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });


   var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         title: "About this calendar demo",
         width: 600,
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            close : function() {
               $about.dialog("close");
            }
         }
      }).show();
   });

   var $login = $("#login");

   $("#login_button").click(function() {
	   if($(this).data("isLogin"))
	   {
		   //如果已经登录了,再点击就退出
		   $("#login_button span").html("登录");	
		   $("#clear_button,#allbook_button,#test_button,#load_button").hide();
		   //重新更改字
		   $("#logintime").html("");
		　　　$("#usertype").html("游客")
		   $(this).data("isLogin",false);
		   
		   //设置登录部门号为0
		   $(this).data("duty",0);
		   
		   //重新刷新视图
		   $("#calendar").weekCalendar("refresh");
	   }
	   else{
		  $("#error").hide();
	      $login.dialog({
	         title: "登 录",
	         width: 400,
			 resizable:false,
	         close: function() {
	            $login.dialog("destroy");
	            $login.hide();
	         },
	         buttons: {
				"登录" : function(){
					//隐藏错误
					$("#error").hide();
					
					
					//客户端验证
					var name=$("input[name='username']").val();
					var psword=$("input[name='password']").val();

					//正则表达式
					b=/^[a-zA-Z\d]\w{3,13}[a-zA-Z\d]$/;
					if(!b.test(name))
					{
						$("#error").html("错误：用户名应当为5~15个英文（数字）单词").show(1000);
						return false;
					}
					
					if(!b.test(psword))
					{
						$("#error").html("错误：密码应当为5~15个英文单词").show(1000);
						return false;
					}								
 					
					//没有问题后提交表单
					//$("#login form").submit();
			 		
					talkWithServer('action/login.php','login','user',0,"0&"+$('#login form').serialize(),false,function(data){
						if(data=="false")
							$("#error").html("错误：用户名或密码错误！").show(1000);
						else
							//使用js进制重定向
							window.location ="roomadmin.php";
							//showInformation(data,timeIn,timeOut);
					});	
							 
					
				},
				"重置" : function(){				
					//清空输入框
					$("#login input").val("");
					//隐藏错误
					$("#error").hide();
				},
	            "关闭" : function() {               
				   //清空输入框
					$("#login input").val("");
					$login.dialog("close");				
	            }
	         }
	      }).show();
	   }
   });
   
/*
   //注销按钮
   $("#logout_button").click(function(){

		talkWithServer('action/login.php','logout','user',0,0,false,function(data){
			    
				if(data=="success")
					//成功注销，使用js进制重定向
					window.location ="roombooking.php";	
				else
					showInformation(data,timeIn,timeOut);
		});			   
		   
   });
*/

	$("#allbook_button").click(function(){
		
		var allBook=$("#calendar").weekCalendar("serializeEvents");
		html="";
		for(i=0;i<allBook.length;i++)
		{
			html+=allBook[i].title+"<br/>";
		}
		showInformation(html,timeIn,timeOut);	
	});



	function talkWithServer(page,action,tbname,duty,data,isasync,func)
	{
		 jsondata='action='+action+"&duty="+duty+"&data="+data+"&tbname="+tbname;
		 
		 $.ajax({
			 type:"POST",
			 url:page,
			 async:isasync,
			 data:jsondata,
			 success:function(data)
			 {
				 func(data);
			 }
			 
		});	
	}


	//显示提示
	function showInformation(msg,timeIn,timeOut)
	{
		$("#show").html(msg).fadeIn(timeIn);
	}

});
